package com.jhgsys.internal.incentive.service.impl;

import com.jhgsys.internal.base.entity.BaseGoods;
import com.jhgsys.internal.base.entity.BaseUserScoreRecord;
import com.jhgsys.internal.base.service.IBaseGoodsService;
import com.jhgsys.internal.base.service.IBaseUserScoreRecordService;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.incentive.constant.IncentiveRewardConstant;
import com.jhgsys.internal.incentive.dto.IncentiveGoodsOrderDtlDto;
import com.jhgsys.internal.incentive.dto.IncentiveGoodsOrderDto;
import com.jhgsys.internal.incentive.dto.IncentiveGoodsOrderUserDto;
import com.jhgsys.internal.incentive.entity.IncentiveGoodsOrder;
import com.jhgsys.internal.incentive.entity.IncentiveGoodsOrderDtl;
import com.jhgsys.internal.incentive.entity.IncentiveGoodsOrderUser;
import com.jhgsys.internal.incentive.mapper.IncentiveGoodsOrderMapper;
import com.jhgsys.internal.incentive.service.IIncentiveGoodsOrderDtlService;
import com.jhgsys.internal.incentive.service.IIncentiveGoodsOrderService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.incentive.service.IIncentiveGoodsOrderUserService;
import com.jhgsys.internal.system.dto.TenantDto;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 安全奖i订单 Service实现
 *
 * @author zhangwei
 * @date 2024-09-02 11:28:06
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class IncentiveGoodsOrderServiceImpl extends ServiceImpl<IncentiveGoodsOrderMapper, IncentiveGoodsOrder> implements IIncentiveGoodsOrderService {

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IIncentiveGoodsOrderUserService iIncentiveGoodsOrderUserService;

    @Autowired
    private IIncentiveGoodsOrderDtlService iIncentiveGoodsOrderDtlService;

    @Autowired
    private IBaseGoodsService iBaseGoodsService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBaseUserScoreRecordService baseUserScoreRecordService;

    /**
     * 查询（分页）
     *
     * @param request                QueryRequest
     * @param incentiveGoodsOrderDto incentiveGoodsOrder
     * @return IPage<IncentiveGoodsOrder>
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    public IPage<IncentiveGoodsOrderDto> findIncentiveGoodsOrderPage(QueryRequest request, IncentiveGoodsOrderDto incentiveGoodsOrderDto) {
        LambdaQueryWrapper<IncentiveGoodsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveGoodsOrder::getDeletedFlg, 0);
        // TODO 设置查询条件
        if (StringUtils.isNotBlank(incentiveGoodsOrderDto.getOrderNo())) {
            queryWrapper.like(IncentiveGoodsOrder::getOrderNo, incentiveGoodsOrderDto.getOrderNo());
        }
        if (StringUtils.isNotBlank(incentiveGoodsOrderDto.getTenantId())) {
            queryWrapper.eq(IncentiveGoodsOrder::getTenantId, incentiveGoodsOrderDto.getTenantId());
        }
        if (StringUtils.isNotBlank(incentiveGoodsOrderDto.getApplyStartDate())) {
            LocalDate date = LocalDate.parse(incentiveGoodsOrderDto.getApplyStartDate());
            queryWrapper.ge(IncentiveGoodsOrder::getOrderDate, date);
        }
        if (StringUtils.isNotBlank(incentiveGoodsOrderDto.getApplyEndDate())) {
            LocalDate date = LocalDate.parse(incentiveGoodsOrderDto.getApplyEndDate());
            queryWrapper.le(IncentiveGoodsOrder::getOrderDate, date);
        }
        if (StringUtils.isNotBlank(incentiveGoodsOrderDto.getGoodsOrderType())) {
            queryWrapper.eq(IncentiveGoodsOrder::getGoodsOrderType, incentiveGoodsOrderDto.getGoodsOrderType());
        }
        if(StringUtils.isNotBlank(incentiveGoodsOrderDto.getStatus())){
            queryWrapper.eq(IncentiveGoodsOrder::getStatus,incentiveGoodsOrderDto.getStatus());
        }
        queryWrapper.orderByDesc(IncentiveGoodsOrder::getExchangeDate).orderByDesc(IncentiveGoodsOrder::getOrderDate);
        Page<IncentiveGoodsOrder> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        Page<IncentiveGoodsOrder> orderPage = this.page(page, queryWrapper);
        List<IncentiveGoodsOrder> records = orderPage.getRecords();
        Page<IncentiveGoodsOrderDto> orderDtoPage = new Page<>();
        if (!records.isEmpty()) {
            List<IncentiveGoodsOrderDto> incentiveGoodsOrderDtoList;
            Set<String> tenantIdSet = records.stream().map(IncentiveGoodsOrder::getTenantId).collect(Collectors.toSet());
            Set<String> goodsOrderIdSet = records.stream().map(IncentiveGoodsOrder::getGoodsOrderId).collect(Collectors.toSet());
            // tenantId和公司tenantName对应的map集合
            TenantDto tenantDto = new TenantDto();
            tenantDto.setTenantIds(tenantIdSet);
            Map<String, String> tenantMap = tenantService.getTenantMapByIdSet(tenantDto);
            // goodsOrderId和申请人列表对应的map集合
            IncentiveGoodsOrderUserDto incentiveGoodsOrderUserDto = new IncentiveGoodsOrderUserDto();
            incentiveGoodsOrderUserDto.setGoodsOrderIdSet(goodsOrderIdSet);
            Map<String, List<IncentiveGoodsOrderUser>> userMap = iIncentiveGoodsOrderUserService.getUserMapByIdSet(incentiveGoodsOrderUserDto);
            incentiveGoodsOrderDtoList = records.stream().map(record -> {
                IncentiveGoodsOrderDto dto = new IncentiveGoodsOrderDto();
                BeanUtils.copyProperties(record, dto);
                dto.setTenantName(tenantMap.getOrDefault(record.getTenantId(), ""));
                List<IncentiveGoodsOrderUser> userList = userMap.getOrDefault(record.getGoodsOrderId(),new ArrayList<>());
                List<IncentiveGoodsOrderUserDto> userDtoList = BeanHelper.copyWithCollection(userList, IncentiveGoodsOrderUserDto.class);
                dto.setUserList(userDtoList);
                return dto;
            }).collect(Collectors.toList());
            orderDtoPage.setCurrent(orderPage.getCurrent());
            orderDtoPage.setSize(orderPage.getSize());
            orderDtoPage.setTotal(orderPage.getTotal());
            orderDtoPage.setRecords(incentiveGoodsOrderDtoList);
        }
        return orderDtoPage;
    }

    /**
     * 查询（所有）
     *
     * @param incentiveGoodsOrder incentiveGoodsOrder
     * @return List<IncentiveGoodsOrder>
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    public List<IncentiveGoodsOrder> findIncentiveGoodsOrderList(IncentiveGoodsOrder incentiveGoodsOrder) {
        LambdaQueryWrapper<IncentiveGoodsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveGoodsOrder::getDeletedFlg, 0);
        if(StringUtils.isNotBlank(incentiveGoodsOrder.getRewardApplyId())){
            queryWrapper.eq(IncentiveGoodsOrder::getRewardApplyId,incentiveGoodsOrder.getRewardApplyId());
        }
        // TODO 设置查询条件
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return IncentiveGoodsOrder
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    public IncentiveGoodsOrder findIncentiveGoodsOrderById(String id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     *
     * @param incentiveGoodsOrderDto incentiveGoodsOrder
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createIncentiveGoodsOrder(IncentiveGoodsOrderDto incentiveGoodsOrderDto) throws FebsException {
        // 兑换积分求和
        BigDecimal totalScore = incentiveGoodsOrderDto.getGoodsList().stream().map(item -> item.getExchangeScore().multiply(new BigDecimal(item.getGoodsNumber()))).reduce(BigDecimal.ZERO, BigDecimal::add);
        incentiveGoodsOrderDto.setOrderScore(totalScore.intValue());

        // check用户积分是否足够
        User user = incentiveGoodsOrderDto.getUser();
        // TODO 其他状态
        User byId = userService.findById(user.getUserId());
        if (null == byId) {
            throw new FebsException("【" + user.getUserName() + "】未查到该用户信息，请联系管理员！");
        }
        if (null == byId.getTotalScore()) {
            throw new FebsException("【" + user.getUserName() + "】该用户积分数据异常，请联系管理员！");
        }
        if ((incentiveGoodsOrderDto.getOrderScore() > byId.getTotalScore())) {
            throw new FebsException("【" + user.getUserName() + "】该用户积分不足，请确认！");
        }

        // check库存量
        List<BaseGoods> baseGoodsList = new ArrayList<>();
        List<IncentiveGoodsOrderDtlDto> goodsList = incentiveGoodsOrderDto.getGoodsList();
        for (IncentiveGoodsOrderDtlDto goods : goodsList) {
            // TODO 其他状态
            BaseGoods baseGoodsById = iBaseGoodsService.findBaseGoodsById(goods.getGoodsId());
            if (null == baseGoodsById) {
                throw new FebsException("【" + goods.getGoodsName() + "】该奖品库存中不存在，请确认库存！");
            }
            if (goods.getGoodsNumber() > baseGoodsById.getInventory()) {
                throw new FebsException("【" + goods.getGoodsName() + "】奖品数量超过库存量，请确认！");
            }
            BaseGoods baseGoods = new BaseGoods();
            baseGoods.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
            baseGoods.setUpdatedTime(new Date());
            baseGoods.setGoodsId(goods.getGoodsId());
            baseGoods.setInventory(goods.getGoodsNumber());
            baseGoodsList.add(baseGoods);
        }

        // 插入incentiveGoodsOrder主表
        incentiveGoodsOrderDto.setCreatedTime(new Date());
        incentiveGoodsOrderDto.setExchangeDate(new Date());
        incentiveGoodsOrderDto.setOrderDate(new Date());
        incentiveGoodsOrderDto.setStatus("3");
        incentiveGoodsOrderDto.setOrderNo(this.createOrderNo(incentiveGoodsOrderDto.getTenantId()));
        String str = incentiveGoodsOrderDto.getOrderNo();
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        UUID uuid = UUID.nameUUIDFromBytes(bytes);
        incentiveGoodsOrderDto.setExchangeCode(uuid.toString().replaceAll("-", ""));
        boolean save = this.save(incentiveGoodsOrderDto);
        if (!save) {
            throw new FebsException("安全奖励订单表插入失败，请联系管理员！");
        }

        // 插入incentiveGoodsOrderDtl子表
        incentiveGoodsOrderDto.getGoodsList().forEach(item -> {
            item.setGoodsOrderId(incentiveGoodsOrderDto.getGoodsOrderId());
            item.setCreatedBy(incentiveGoodsOrderDto.getCreatedBy());
            item.setCreatedTime(new Date());
        });
        List<IncentiveGoodsOrderDtl> incentiveGoodsOrderDtls = BeanHelper.copyWithCollection(incentiveGoodsOrderDto.getGoodsList(), IncentiveGoodsOrderDtl.class);
        boolean b = iIncentiveGoodsOrderDtlService.saveBatch(incentiveGoodsOrderDtls);
        if (!b) {
            throw new FebsException("安全奖励订单子表插入失败，请联系管理员！");
        }

        // 插入incentiveGoodsOrderUser表
        IncentiveGoodsOrderUser goodsOrderUser = new IncentiveGoodsOrderUser();
        goodsOrderUser.setGoodsOrderId(incentiveGoodsOrderDto.getGoodsOrderId());
        goodsOrderUser.setTenantId(user.getTenantId());
        goodsOrderUser.setUserId(user.getUserId());
        goodsOrderUser.setUserNo(user.getUserNo());
        goodsOrderUser.setRealName(user.getUname());
        goodsOrderUser.setDeptId(user.getDeptId());
        goodsOrderUser.setDeptName(user.getDeptName());
        goodsOrderUser.setCreatedBy(incentiveGoodsOrderDto.getCreatedBy());
        goodsOrderUser.setCreatedTime(new Date());
        boolean yes = iIncentiveGoodsOrderUserService.save(goodsOrderUser);
        if (!yes) {
            throw new FebsException("安全奖励订单人员表插入失败，请联系管理员！");
        }

        // 批量更新库存
        if (!baseGoodsList.isEmpty()) {
            boolean c = iBaseGoodsService.updateBatchInventory(baseGoodsList);
            if (!c) {
                throw new FebsException("库存更新失败，请联系管理员！");
            }
        }

        // 减用户积分
        User u = new User();
        u.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
        u.setModifyTime(new Date());
        u.setTotalScore(incentiveGoodsOrderDto.getOrderScore());
        u.setUserId(user.getUserId());
        boolean success = userService.updateScore(u);
        if (!success) {
            throw new FebsException("【" + user.getUserName() + "】用户积分更新失败，请联系管理员！");
        }

        // 用户积分使用记录
        BaseUserScoreRecord baseUserScoreRecord = new BaseUserScoreRecord();
        baseUserScoreRecord.setTenantId(byId.getTenantId());
        baseUserScoreRecord.setUserId(byId.getUserId());
        baseUserScoreRecord.setRealName(byId.getUname());
        baseUserScoreRecord.setUserNo(byId.getUserNo());
        baseUserScoreRecord.setDeptId(byId.getDeptId());
        baseUserScoreRecord.setDeptName(user.getDeptName());
        baseUserScoreRecord.setDataSource("99");
        baseUserScoreRecord.setDataTargetId(incentiveGoodsOrderDto.getGoodsOrderId());
        baseUserScoreRecord.setOperateType("2");
        baseUserScoreRecord.setOperateDate(new Date());
        baseUserScoreRecord.setOperateScore(incentiveGoodsOrderDto.getOrderScore());
        baseUserScoreRecord.setBeforeScore(byId.getTotalScore());
        baseUserScoreRecord.setAfterScore(byId.getTotalScore() - incentiveGoodsOrderDto.getOrderScore());
        baseUserScoreRecord.setCreatedBy(incentiveGoodsOrderDto.getCreatedBy());
        baseUserScoreRecord.setCreatedTime(new Date());
        boolean save1 = baseUserScoreRecordService.save(baseUserScoreRecord);
        if (!save1) {
            throw new FebsException("用户积分使用记录更新失败，请联系管理员！");
        }
    }

    @Override
    @Transactional
    public void createPeaceIncentiveGoodsOrder(IncentiveGoodsOrderDto incentiveGoodsOrderDto) throws FebsException {
        incentiveGoodsOrderDto.setCreatedTime(new Date());
        incentiveGoodsOrderDto.setExchangeDate(new Date());
        incentiveGoodsOrderDto.setOrderDate(new Date());
        incentiveGoodsOrderDto.setStatus(IncentiveRewardConstant.ORDER_STATUS.WAIT_RECEIVE);
        incentiveGoodsOrderDto.setOrderNo(this.createOrderNo(incentiveGoodsOrderDto.getTenantId()));
        String str = incentiveGoodsOrderDto.getOrderNo();
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        UUID uuid = UUID.nameUUIDFromBytes(bytes);
        incentiveGoodsOrderDto.setExchangeCode(uuid.toString().replaceAll("-", ""));
        boolean save = this.save(incentiveGoodsOrderDto);
        if(save){
            if (!CollectionUtils.isEmpty(incentiveGoodsOrderDto.getGoodsList())) {
                List<IncentiveGoodsOrderDtl> goodsList = BeanHelper.copyWithCollection(incentiveGoodsOrderDto.getGoodsList(),IncentiveGoodsOrderDtl.class);
                goodsList.forEach(item->{
                    item.setGoodsOrderId(incentiveGoodsOrderDto.getGoodsOrderId());
                });
                iIncentiveGoodsOrderDtlService.saveBatch(goodsList);
            }

            if (!CollectionUtils.isEmpty(incentiveGoodsOrderDto.getUserList())) {
                incentiveGoodsOrderDto.getUserList().forEach(item->{
                    item.setGoodsOrderId(incentiveGoodsOrderDto.getGoodsOrderId());
                });
                List<IncentiveGoodsOrderUser> userList = BeanHelper.copyWithCollection(incentiveGoodsOrderDto.getUserList(), IncentiveGoodsOrderUser.class);
                iIncentiveGoodsOrderUserService.saveBatch(userList);
            }
        }
    }

    /**
     * 发放
     *
     * @param incentiveGoodsOrderDto incentiveGoodsOrder
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handOutIncentiveGoodsOrder(IncentiveGoodsOrderDto incentiveGoodsOrderDto) throws FebsException {
        // check库存量
        List<IncentiveGoodsOrderDtlDto> goodsList = incentiveGoodsOrderDto.getGoodsList();
        // 人数
        int peopleNum = incentiveGoodsOrderDto.getUserList().size();
        List<BaseGoods> baseGoodsList = new ArrayList<>();
        for (IncentiveGoodsOrderDtlDto goods : goodsList) {
            // TODO 其他状态
            if(!IncentiveRewardConstant.GOODS_ORDER_TYPE.PEACE.equals(incentiveGoodsOrderDto.getGoodsOrderType())){
                BaseGoods baseGoodsById = iBaseGoodsService.findBaseGoodsById(goods.getGoodsId());
                if (null == baseGoodsById) {
                    throw new FebsException("【" + goods.getGoodsName() + "】该奖品库存中不存在，请确认库存！");
                }
                // 奖品数量 * 人数 不能超过库存锁定数量
                if (goods.getGoodsNumber() * peopleNum > baseGoodsById.getLockNumber()) {
                    throw new FebsException("【" + goods.getGoodsName() + "】发放数量超过锁定库存数量，请确认！");
                }
                BaseGoods baseGoods = new BaseGoods();
                baseGoods.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
                baseGoods.setUpdatedTime(new Date());
                baseGoods.setGoodsId(goods.getGoodsId());
                baseGoods.setInventory(goods.getGoodsNumber());
                baseGoodsList.add(baseGoods);
            }
            if (!baseGoodsList.isEmpty()) {
                boolean b = iBaseGoodsService.updateBatchInventory(baseGoodsList);
                if (!b) {
                    throw new FebsException("库存更新失败，请联系管理员！");
                }
            }

        }


        // 更新主表状态
        IncentiveGoodsOrder incentiveGoodsOrder = new IncentiveGoodsOrder();
        incentiveGoodsOrder.setGoodsOrderId(incentiveGoodsOrderDto.getGoodsOrderId());
        incentiveGoodsOrder.setStatus("3");
        incentiveGoodsOrder.setUpdatedTime(new Date());
        incentiveGoodsOrder.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
        this.saveOrUpdate(incentiveGoodsOrder);
    }

    /**
     * 取消兑现
     *
     * @param incentiveGoodsOrderDto incentiveGoodsOrder
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelIncentiveGoodsOrder(IncentiveGoodsOrderDto incentiveGoodsOrderDto) throws FebsException {
        // 批量还原锁定库存
        List<IncentiveGoodsOrderDtlDto> goodsList = incentiveGoodsOrderDto.getGoodsList();
        List<BaseGoods> baseGoodsList = goodsList.stream().map(goods -> {
            BaseGoods baseGoods = new BaseGoods();
            baseGoods.setGoodsId(goods.getGoodsId());
            baseGoods.setLockNumber(goods.getGoodsNumber());
            baseGoods.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
            baseGoods.setUpdatedTime(new Date());
            return baseGoods;
        }).collect(Collectors.toList());
        boolean r = iBaseGoodsService.updateBatchLockInventory(baseGoodsList);
        if (!r) {
            throw new FebsException("库存更新失败，请联系管理员！");
        }
        // 用户积分记录表记录
        List<User> list = new ArrayList<>();
        List<BaseUserScoreRecord> recordList = new ArrayList<>();
        List<IncentiveGoodsOrderUserDto> userList = incentiveGoodsOrderDto.getUserList();
        List<String> userIdList = userList.stream().map(IncentiveGoodsOrderUser::getUserId).collect(Collectors.toList());
        List<User> userByUserIds = userService.findUserByUserIds(userIdList);
        Map<String, User> userMap = new HashMap<>();
        if (!userByUserIds.isEmpty()) {
            userMap = userByUserIds.stream().collect(Collectors.toMap(User::getUserId, item -> item));
        }
        for (IncentiveGoodsOrderUser goodsOrderUser : userList) {
            User u = new User();
            u.setUserId(goodsOrderUser.getUserId());
            u.setTotalScore(incentiveGoodsOrderDto.getOrderScore());
            u.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
            u.setModifyTime(new Date());
            list.add(u);
            User user = userMap.getOrDefault(goodsOrderUser.getUserId(), null);
            if (null != user) {
                BaseUserScoreRecord baseUserScoreRecord = new BaseUserScoreRecord();
                baseUserScoreRecord.setTenantId(user.getTenantId());
                baseUserScoreRecord.setUserId(user.getUserId());
                baseUserScoreRecord.setRealName(user.getUname());
                baseUserScoreRecord.setUserNo(user.getUserNo());
                baseUserScoreRecord.setDeptId(user.getDeptId());
                baseUserScoreRecord.setDeptName(goodsOrderUser.getDeptName());
                baseUserScoreRecord.setDataSource("99");
                baseUserScoreRecord.setDataTargetId(incentiveGoodsOrderDto.getGoodsOrderId());
                baseUserScoreRecord.setOperateType("1");
                baseUserScoreRecord.setOperateDate(new Date());
                baseUserScoreRecord.setOperateScore(incentiveGoodsOrderDto.getOrderScore());
                baseUserScoreRecord.setBeforeScore(user.getTotalScore());
                baseUserScoreRecord.setAfterScore(user.getTotalScore() + incentiveGoodsOrderDto.getOrderScore());
                baseUserScoreRecord.setCreatedBy(incentiveGoodsOrderDto.getCreatedBy());
                baseUserScoreRecord.setCreatedTime(new Date());
                recordList.add(baseUserScoreRecord);
            }
        }
        boolean save1 = baseUserScoreRecordService.saveBatch(recordList);
        if (!save1) {
            throw new FebsException("用户积分使用记录更新失败，请联系管理员！");
        }
        // 归还用户积分
        boolean b = userService.updateBatchScore(list);
        if (!b) {
            throw new FebsException("用户积分更新失败，请联系管理员！");
        }
        // 更改主表状态
        IncentiveGoodsOrder incentiveGoodsOrder = new IncentiveGoodsOrder();
        incentiveGoodsOrder.setGoodsOrderId(incentiveGoodsOrderDto.getGoodsOrderId());
        incentiveGoodsOrder.setStatus("4");
        incentiveGoodsOrder.setUpdatedTime(new Date());
        incentiveGoodsOrder.setUpdatedBy(incentiveGoodsOrderDto.getCreatedBy());
        this.saveOrUpdate(incentiveGoodsOrder);
    }

    /**
     * 修改
     *
     * @param incentiveGoodsOrder incentiveGoodsOrder
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    @Transactional
    public void updateIncentiveGoodsOrder(IncentiveGoodsOrder incentiveGoodsOrder) {
        incentiveGoodsOrder.setUpdatedTime(new Date());
        this.saveOrUpdate(incentiveGoodsOrder);
    }

    /**
     * 逻辑删除
     *
     * @param incentiveGoodsOrder    incentiveGoodsOrder
     * @param incentiveGoodsOrderIds incentiveGoodsOrderIds
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    @Transactional
    public void deleteIncentiveGoodsOrder(IncentiveGoodsOrder incentiveGoodsOrder, String incentiveGoodsOrderIds) {
        List<String> list = Arrays.asList(incentiveGoodsOrderIds.split(StringPool.COMMA));
        this.baseMapper.update(incentiveGoodsOrder, new LambdaQueryWrapper<IncentiveGoodsOrder>().in(IncentiveGoodsOrder::getGoodsOrderId, list));
    }

    /**
     * 物理删除
     *
     * @param incentiveGoodsOrderIds incentiveGoodsOrderIds
     * @author zhangwei
     * @date 2024-09-02 11:28:06
     */
    @Override
    @Transactional
    public void physicallyDeleteIncentiveGoodsOrder(String incentiveGoodsOrderIds) {
        List<String> list = Arrays.asList(incentiveGoodsOrderIds.split(StringPool.COMMA));
        LambdaQueryWrapper<IncentiveGoodsOrder> wapper = new LambdaQueryWrapper<>();
        wapper.in(IncentiveGoodsOrder::getGoodsOrderId, list);
        this.remove(wapper);
    }

    /**
     * 生成编号 年+公司编码+序列号（5位）
     *
     * @param tenantId 公司ID
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public String createOrderNo(String tenantId) throws FebsException {
        String examineNo = "";

        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Tenant tenant = tenantService.getById(tenantId);
        if (null == tenant || org.apache.commons.lang3.StringUtils.isBlank(tenant.getTenantCode())) {
            throw new FebsException("安全奖励订单编号生成异常");
        }
        String tenantCode = tenant.getTenantCode();
        LambdaQueryWrapper<IncentiveGoodsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveGoodsOrder::getTenantId, tenantId);
        queryWrapper.apply("DATE_FORMAT(created_time,'%Y') = DATE_FORMAT(NOW(),'%Y')");
        List<IncentiveGoodsOrder> incentiveGoodsOrderList = this.baseMapper.selectList(queryWrapper);
        int length = incentiveGoodsOrderList.size();
        String yearStr = String.valueOf(calendar.get(Calendar.YEAR));
        String sequencePrefix = "";
        if (length < 99999) {
            sequencePrefix = String.format("%5d", length + 1).replace(" ", "0");
        } else {
            sequencePrefix = String.format("%8d", length + 1).replace(" ", "0");
        }
        examineNo = yearStr + tenantCode + sequencePrefix;
        return examineNo;
    }
}
